package com.uxsino.reactorq.commons;

import java.util.function.Consumer;

import org.slf4j.Logger;

/**
 * to catch all exceptions throwed by a consumer
 *
 * @param <T>
 */
public class CatchConsumer<T> implements Consumer<T> {
    private Logger logger;

    private Consumer<? super T> innerConsumer;

    public CatchConsumer(Consumer<? super T> consumer, Logger logger) {
        innerConsumer = consumer;
        this.logger = logger;
    }

    public static <T> CatchConsumer<T> Catch(Consumer<? super T> consumer, Logger logger) {
        return new CatchConsumer<>(consumer, logger);
    }

    @Override
    public void accept(T t) {

        try {
            innerConsumer.accept(t);
        } catch (Throwable e) {
            logger.error("{}", e);
        }
    }

}
